/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.server.version.model;

import java.util.NoSuchElementException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.RepositoryException;
import offset.nodes.Constants;

/**
 *
 * @author Walter L�tgenau
 */
public class FrozenNodeNodeIterator implements NodeIterator {
    NodeIterator iterator;

    public FrozenNodeNodeIterator(NodeIterator iterator) throws RepositoryException {
        this.iterator = iterator;
    }

    @Override
    public void skip(long skipNum) {
        iterator.skip(skipNum);
    }

    @Override
    public long getSize() {
        return iterator.getSize();
    }

    @Override
    public long getPosition() {
        return iterator.getPosition();
    }

    @Override
    public Node nextNode() {
        try {
            Node node = iterator.nextNode();
            if (node.isNodeType(Constants.NT_FROZEN_NODE))
                return new FrozenNode(node);
            else if (node.isNodeType(Constants.NT_VERSIONED_CHILD)) {
                VersionModel model = new VersionModel(node.getSession());
                return new FrozenNode(model.getFrozenNode(node), node.getParent(), node.getName());
            }
            return node;
        } catch (RepositoryException ex) {
            Logger.getLogger(FrozenNodeNodeIterator.class.getName()).log(Level.SEVERE, null, ex);
            throw new NoSuchElementException();
        }
    }

    @Override
    public boolean hasNext() {
        return iterator.hasNext();
    }

    @Override
    public Object next() {
        return nextNode();
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
